package com.xinggq.pay.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinggq.pay.service.entity.PayCallbackEntity;
import com.xinggq.pay.service.enums.CallbackStatusEnum;
import com.xinggq.pay.service.mapper.ChannelCallbackMapper;
import com.xinggq.pay.service.service.ChannelCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 支付渠道回调记录服务实现类
 *
 * @author system
 * @since 2025/1/10
 */
@Slf4j
@Service
public class ChannelCallbackServiceImpl implements ChannelCallbackService {

  @Autowired
  private ChannelCallbackMapper channelCallbackMapper;

  @Override
  public boolean save(PayCallbackEntity entity) {
    if (entity == null) {
      throw new IllegalArgumentException("回调记录实体不能为空");
    }
    return channelCallbackMapper.insert(entity) > 0;
  }


  @Override
  public PayCallbackEntity findById(Long id) {
    if (id == null || id <= 0) {
      throw new IllegalArgumentException("ID不能为空或小于等于0");
    }
    return channelCallbackMapper.selectById(id);
  }

  @Override
  public boolean updateErrorMsg(Long callbackId, String errorMsg) {
    if (callbackId == null || callbackId <= 0) {
      throw new IllegalArgumentException("回调ID不能为空或小于等于0");
    }

    // 截取错误信息，数据库字段长度为varchar(500)
    String truncatedErrorMsg = errorMsg;
    if (errorMsg != null && errorMsg.length() > 500) {
      truncatedErrorMsg = errorMsg.substring(0, 500);
    }

    PayCallbackEntity entity = new PayCallbackEntity();
    entity.setId(callbackId);
    entity.setErrorMsg(truncatedErrorMsg);
    entity.setCallbackStatus(CallbackStatusEnum.FAIL.getCode());

    return channelCallbackMapper.updateById(entity) > 0;
  }

  @Override
  public PayCallbackEntity findBySuccessTradeNo(String tradeNo) {
    if (!StringUtils.hasText(tradeNo)) {
      throw new IllegalArgumentException("支付单号不能为空");
    }

    LambdaQueryWrapper<PayCallbackEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(PayCallbackEntity::getTradeNo, tradeNo)
        .eq(PayCallbackEntity:: getCallbackStatus, CallbackStatusEnum.SUCCESS.getCode())
        .last("LIMIT 1");

    return channelCallbackMapper.selectOne(queryWrapper);
  }
}